package com.rp.configure.controller;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.rp.common.result.ResultDTO;
import com.rp.common.utils.NullIs;
import com.rp.common.utils.Selectway;
import com.rp.configure.entity.Alarm;
import com.rp.configure.entity.AlarmAll;
import com.rp.configure.entity.Subject;
import com.rp.configure.entity.UserSubject;
import com.rp.configure.service.AlarmAllService;
import com.rp.configure.service.SubjectService;
import com.rp.configure.service.UserSubjectService;
import com.rp.system.user.entity.SysUser;
import com.rp.system.user.service.SysUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author vicente
 * @since 2021-07-14
 */
@RestController
@RequestMapping("/subject")
@Api(tags="项目管理")
public class SubjectController {
    @Autowired
    private SubjectService subjectService;
    @Autowired
    private UserSubjectService userSubjectService;
    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private AlarmAllService alarmAllService;

    @ApiOperation(value = "分页列表")
//    @RequiresRoles(value={"admin","vip"},logical = Logical.OR)
    @GetMapping(value = "/list_page")
    public ResultDTO<IPage<Subject>> listPage(@RequestParam(value = "pageNum", defaultValue = "1") int pageNum,
                                           @RequestParam(value = "pageSize", defaultValue = "20") int pageSize) {
        QueryWrapper<Subject> queryWrapper = new QueryWrapper<Subject>();
        queryWrapper.orderByDesc("create_time");
        return ResultDTO.success().data(subjectService.page(new Page<>(pageNum, pageSize), queryWrapper));
    }
    @ApiOperation(value = "列表")
//    @RequiresRoles(value={"admin","vip"},logical = Logical.OR)
    @GetMapping(value = "/list")
    public ResultDTO<List<Subject>> list() {
     return ResultDTO.success().data(subjectService.list());
    }
    @ApiOperation(value = "分页列表/根据用户id")
//    @RequiresRoles(value={"admin","vip"},logical = Logical.OR)
    @GetMapping(value = "/page_userId")
    public ResultDTO<IPage<Subject>> PageByUserId(@RequestParam(value = "pageNum", defaultValue = "1") int pageNum,
                                                 @RequestParam(value = "pageSize", defaultValue = "20") int pageSize,
                                                 @RequestParam(value = "userId", defaultValue = "20") String userId
                                                 ) {

        if (!NullIs.isEmpty(userId)){
            IPage<Subject> list=subjectService.listByUserId(new Page<Subject>(pageNum,pageSize),userId);

            list.getRecords().forEach(l->{
                List<Alarm> list1 = alarmAllService.listBySubject(l.getId());
                ArrayList<String> strings = new ArrayList<>();
                list1.forEach(li->{strings.add(li.getId());});
                l.setAlarmId(strings.toString());
                l.setAlarms(list1);
            });
            return ResultDTO.success().data(list);
        }else {
            return ResultDTO.USER_NOT_LOGGED_IN().message("用户未登录,请登录后重新操作");
        }
    }
    @ApiOperation(value = "根据项目id")
//    @RequiresRoles(value={"admin","vip"},logical = Logical.OR)
    @GetMapping(value = "/list_subjectId")
    public ResultDTO<Subject> listBySubjectId(@RequestParam(value = "subjectId") String subjectId
    ) {
        QueryWrapper<Subject> queryWrapper = new QueryWrapper<Subject>();
        queryWrapper.eq("id",subjectId);
        Subject one = subjectService.getOne(queryWrapper);
        List<Alarm> list = alarmAllService.listBySubject(subjectId);
        if (!NullIs.isEmpty(list)){
        one.setAlarms(list);}
        return ResultDTO.success().data(one);

    }
    @ApiOperation(value = "根据用户id")
//    @RequiresRoles(value={"admin","vip"},logical = Logical.OR)
    @GetMapping(value = "/list_userId")
    public ResultDTO<List<Subject>> listByUserId(
            @RequestParam(value = "userId") String userId
    ) {
        List<Subject> list=subjectService.getList(userId);
        list.forEach(subject -> {
            subject.setAlarms((ArrayList<Alarm>) alarmAllService.listBySubject(subject.getId()));
        });
        return ResultDTO.success().data(list);

    }
    @PostMapping("/insert")
    @ApiOperation(value = "增加")
    @Transactional
//    @RequiresRoles(value={"admin","vip"},logical = Logical.OR)
    public ResultDTO insert(@RequestBody Subject subject) {

        UserSubject userSubject = new UserSubject();
        System.out.println("userID"+subject.getUserId());
        if (!NullIs.isEmpty(subject.getUserId())){
            userSubject.setUserId(subject.getUserId());
            boolean save = subjectService.save(subject);
            userSubject.setSubjectId(subject.getId());
            userSubjectService.save(userSubject);
            JSONArray objects = JSON.parseArray(subject.getAlarmId());
            objects.forEach(o -> {
                AlarmAll all = new AlarmAll();
                all.setAlarmId(o.toString()).setSubjectId(subject.getId());
                alarmAllService.save(all);
            });

            return ResultDTO.tf(save);
        }else{
            return ResultDTO.USER_NOT_LOGGED_IN().message("用户未登录");
        }

    }

    @PutMapping("/update")
    @ApiOperation(value = "修改")
//    @RequiresRoles(value={"admin","vip"},logical = Logical.OR)
    public ResultDTO update(@RequestBody Subject subject) {
        QueryWrapper<AlarmAll> wrapper = new QueryWrapper<>();
        wrapper.eq("subject_id",subject.getId());
        alarmAllService.remove(wrapper);
        if (!NullIs.isEmpty(subject.getAlarmId())){
        Object json1 = JSON.toJSON(subject.getAlarmId());
        JSONArray objects = JSONArray.parseArray(json1.toString());
        for (int i = 0; i < objects.size(); i++) {
            AlarmAll all = new AlarmAll();
            all.setAlarmId(objects.get(i).toString()).setSubjectId(subject.getId());
            alarmAllService.save(all);
        }
        }

        return ResultDTO.tf(subjectService.updateById(subject));
    }

    @DeleteMapping("/delete")
    @ApiOperation(value = "删除")
//    @RequiresRoles(value={"admin","vip"},logical = Logical.OR)
    @Transactional
    public ResultDTO delete(@RequestBody @ApiParam(value = "id", required = true) String id) {
        QueryWrapper<UserSubject> wrapper = new QueryWrapper<>();
        wrapper.eq("subject_id",id);

        return ResultDTO.tf(userSubjectService.remove(wrapper)&subjectService.removeById(id));
    }

    @DeleteMapping("/deleteAll")
    @ApiOperation(value = "批量删除")
//    @RequiresRoles(value={"admin","vip"},logical = Logical.OR)
    public ResultDTO deleteAll(@RequestBody @ApiParam(value = "id(英文逗号隔开)", required = true) String ids) {


        return ResultDTO.tf(subjectService.removeByIds(Arrays.asList(ids.split(","))));
    }

}
